import db from '~/DB';
import { RestRequest } from 'msw';
import { Token } from '~~/DB/types/token.d';

interface T extends RestRequest {
  token?: string;
  tokenInfo?: Token;
}

export function getToken(req: T) {
  // console.log('🚀 ~ file: token.ts:11 ~ getToken ~ req:', req);
  if (!req.token) {
    const _token = req.headers.get('Authorization');
    if (_token) {
      const token = _token.slice(7);
      req.token = token;
    }
  }
  return req.token;
}

export async function getTokenInfo(req: T) {
  // console.log('🚀 ~ file: token.ts:22 ~ getTokenInfo ~ req:', req);
  if (!req.tokenInfo) {
    const token = getToken(req);
    // console.log('🚀 ~ file: token.ts:26 ~ getTokenInfo ~ token:', token);
    if (token) {
      const tokenInfo = await db.tokens.get({
        token,
      });
      req.tokenInfo = tokenInfo;
    }
  }

  return req.tokenInfo;
}
